package com.itheima.web.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

// 创建Cookie保存到浏览器
@WebServlet("/aServlet")
public class AServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = "张三";
        String encode = URLEncoder.encode(username, "UTF-8");

        // 1.使用构造方法创建Cookie对象
        Cookie cookie = new Cookie("username", encode);

        // 设置Cookie的过期时间,单位是秒 (一个星期)
        cookie.setMaxAge(0);

        // 2.将Cookie写到浏览器端
        response.addCookie(cookie);
    }
}
